package com.xopencode.decimal;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * @author Mcb
 * @date 2022/4/4
 * @apiNote
 */
public class DecimalDemo {
    public static void main(String[] args) {
        double a = 4.0;
        double b = 3.6;
        System.out.println(a-b);
        BigDecimal bigDecimal = new BigDecimal("4.0");
        BigDecimal bigDecimal2 = new BigDecimal("3.6");
        System.out.println(bigDecimal.subtract(bigDecimal2));
        System.out.println(bigDecimal.subtract(bigDecimal2).doubleValue());
        System.out.println(new BigDecimal(1));
        System.out.println("----------------------------------");
        System.out.println(formatToNumber(new BigDecimal("3.435")));
        System.out.println(formatToNumber(new BigDecimal(0)));
        System.out.println(formatToNumber(new BigDecimal("0.00")));
        System.out.println(formatToNumber(new BigDecimal("0.001")));
        System.out.println(formatToNumber(new BigDecimal("0.006")));
        System.out.println(formatToNumber(new BigDecimal("0.206")));
        System.out.println("----------------------------------");
        System.out.println(placeholder(new BigDecimal("0.21")));

        DecimalFormat f1 = new DecimalFormat("0.0");
        System.out.println("0:"+f1.format(new BigDecimal("0.1")));

        DecimalFormat f2 = new DecimalFormat("#.#");
        System.out.println("#:"+f2.format(new BigDecimal("0.1")));

        DecimalFormat f3 = new DecimalFormat("0");
        System.out.println(f3.format(new BigDecimal("123.123")));
    }

    public static String formatToNumber(BigDecimal bigDecimal){
        DecimalFormat df = new DecimalFormat("#.00");
        if(bigDecimal.compareTo(BigDecimal.ZERO)==0) {
            return "0.00";
        }else if(bigDecimal.compareTo(BigDecimal.ZERO)>0&&bigDecimal.compareTo(new BigDecimal(1))<0){
            return "0"+df.format(bigDecimal).toString();
        }else {
            return df.format(bigDecimal).toString();
        }
    }

    /**
     * 测试#号占位符对数字0的修饰
     * @param bigDecimal
     * @return
     */
    public static String placeholder(BigDecimal bigDecimal){
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(bigDecimal).toString();
    }
}
